﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Collections.Generic;
using System.Windows;
using Microsoft.VisualStudio.PlatformUI;
using AppRes = WindowsPhoneCommands.Resources;
using System;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Collections;


// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{

    /// <summary>
    /// Interaction logic for XapDeploy.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class InspectAppSettingsDialog : DialogWindow
    // ReSharper restore RedundantExtendsListEntry
    {

        public string RootNode { get; set; }
        private bool _loaded; 
        public Dictionary<string, object> Settings { get; set; }

        public InspectAppSettingsDialog()
        {
            InitializeComponent();
            Background = VsTheming.GetDialogBackground();
            Foreground = VsTheming.GetWindowText();
            Title = AppRes.ToolWindowTitle + " " + AppRes.InspectAppSettings;
            Loaded += InspectAppSettingsDialogLoaded;
        }

        private void InspectAppSettingsDialogLoaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                NameProject.Text = RootNode;
                if (Settings == null)
                {
                    Close();
                }
                try
                {
                    CreateTree();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            _loaded = true;
        }

        private void CreateTree()
        {
            TreeSettings.Items.Clear();
            //create treeview
            var root = new TreeViewWithIcons
            {
                HeaderText = AppRes.AppSettings,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.ApplicationOnIcon,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                CheckedVisibled = false
            };
            TreeSettings.Items.Add(root);
            foreach (var nodeset in Settings)
            {
                var header = nodeset.Key;
                var isKnow = true;
                var isList = false;
                if (nodeset.Value is XmlNode)
                {
                    isKnow = false;
                    var key = header.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (key.Length == 1)
                    {
                        header += " (Custom Type)";
                    }
                    else
                    {
                        header = key[0] + " (" + key[1] + ")";
                    }
                }
                else
                {
                    var ktype = nodeset.Value.GetType();
                    var listtype = nodeset.Value as IList;
                    if (listtype != null)
                    {
                        isList = true;
                        if (listtype.Count > 0)
                        {
                            if (ktype.IsGenericType)
                            {
                                var itemType = ktype.GetGenericArguments()[0];
                                header += " (" + itemType.Name + "[" + listtype.Count + "])";
                            }
                            else
                            {
                                header += " (" + ktype.Name.Replace("[]","") + "[" + listtype.Count + "])";
                            }
                        }
                        else
                        {
                            if (ktype.IsGenericType)
                            {
                                header += " (IList[0])";
                            }
                            else
                            {
                                header += " (" + ktype.Name.Replace("[]", "") + "[0])";
                            }
                        }
                    }
                    else
                    {
                        header += " (" + ktype.Name + ")";
                    }
                }
                var node = new TreeViewWithIcons
                {
                    HeaderText = header,
                    Tag = null,
                    Icon =
                        new BitmapImage(
                        new Uri(Constants.RootResource + Constants.KeyIcon,
                                UriKind.RelativeOrAbsolute)),
                    IconHeight = 16,
                    IconWidth = 16,
                    CheckedVisibled = false
                };
                if (isKnow)
                {
                    if (!isList)
                    {
                        node.Items.Add(new TreeViewWithIcons
                        {
                            HeaderText = nodeset.Value.ToString(),
                            Tag = null,
                            Icon =
                                new BitmapImage(
                                new Uri(Constants.RootResource + Constants.MineArrowIcon,
                                        UriKind.RelativeOrAbsolute)),
                            IconHeight = 9,
                            IconWidth = 6,
                            CheckedVisibled = false
                        });
                    }
                    else
                    {
                        var listtype = nodeset.Value as IList;
                        foreach (var item in listtype)
                        {
                            node.Items.Add(new TreeViewWithIcons
                            {
                                HeaderText = item.ToString(),
                                Tag = null,
                                Icon =
                                    new BitmapImage(
                                    new Uri(Constants.RootResource + Constants.MineArrowIcon,
                                            UriKind.RelativeOrAbsolute)),
                                IconHeight = 9,
                                IconWidth = 6,
                                CheckedVisibled = false
                            });
                        }
                    }
                }
                else
                {
                    var nodev = nodeset.Value as XmlNode;
                    if (!nodev.HasChildNodes)
                    {
                        node.Items.Add(new TreeViewWithIcons
                        {
                            HeaderText = nodev.InnerText,
                            Tag = null,
                            Icon =
                                new BitmapImage(
                                new Uri(Constants.RootResource + Constants.MineArrowIcon,
                                        UriKind.RelativeOrAbsolute)),
                            IconHeight = 9,
                            IconWidth = 6,
                            CheckedVisibled = false
                        });
                    }
                    else
                    {
                        node = CreatesubTree(node, nodev);
                    }
                }
                root.Items.Add(node);
            }
            root.IsExpanded = true;
        }

        private static TreeViewWithIcons CreatesubTree(TreeViewWithIcons mainode,XmlNode nodev)
        {
            foreach (XmlNode itemnode in nodev.ChildNodes)
            {
                if (itemnode.HasChildNodes)
                {
                    var subitem = new TreeViewWithIcons
                    {
                        HeaderText = itemnode.LocalName,
                        Tag = null,
                        Icon =
                            new BitmapImage(
                            new Uri(Constants.RootResource + Constants.PropertyIcon,
                                    UriKind.RelativeOrAbsolute)),
                        IconHeight = 16,
                        IconWidth = 16,
                        CheckedVisibled = false
                    };
                    mainode.Items.Add(CreatesubTree(subitem, itemnode));
                }
                else
                {
                    mainode.Items.Add(new TreeViewWithIcons
                    {
                        HeaderText = itemnode.InnerText,
                        Tag = null,
                        Icon =
                            new BitmapImage(
                            new Uri(Constants.RootResource + Constants.MineArrowIcon,
                                    UriKind.RelativeOrAbsolute)),
                        IconHeight = 9,
                        IconWidth = 6,
                        CheckedVisibled = false
                    });
                }
            }
            return mainode;
        }
    }
}
